<?php

namespace plugin\enterprise\app\support\Cores;

use Illuminate\Support\Str;
use plugin\enterprise\app\Enterprise;
use plugin\owladmin\app\Admin;

class Permission extends \plugin\owladmin\app\support\Cores\Permission
{
    public function authIntercept($request): array
    {
        if (!Enterprise::config('enterprise.auth.enable')) {
            return [false, null];
        }

        $excepted = collect(Enterprise::config('enterprise.auth.except', []))
            ->merge($this->authExcept)
            ->map(fn($path) => $this->pathFormatting($path))
            // webman
            ->contains(fn($except) => collect($except == '/' ? $except : trim($except, '/'))->contains(fn($pattern) => Str::is($pattern, trim($request->path(), '/'))));
        $user = Enterprise::guard()->user();
        return [!$excepted && empty($user), $user];
    }

    private function pathFormatting($path): string
    {
        $prefix = '/' . trim(Enterprise::config('enterprise.route.prefix'), '/');

        $prefix = ($prefix === '/') ? '' : $prefix;

        $path = trim($path, '/');

        if (is_null($path) || $path === '') {
            return $prefix ?: '/';
        }
        return $prefix . '/' . $path;
    }
}